package com.liao.rent.utils;

import com.alibaba.fastjson2.JSON;
import com.liao.rent.constant.ResultCode;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: ljt
 * @Description: 相应返回工具
 * @pareme response 响应对象 data响应数据
 * @DateTime: 2024/11/26 下午8:31
 **/
public class ResponseUtil {

    /***
     * 返回指定错误
     * @param response
     * @param code 错误码
     * @throws IOException
     */
    public static void write(HttpServletResponse response, ResultCode code) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        PrintWriter writer = response.getWriter();
        String jsonData = JSON.toJSONString(JSON.toJSON(ResultTool.fail(code)));
        writer.println((jsonData));
    }

    /***
     * 返回指定错误
     * @param response
     * @param msg 错误信息
     * @throws IOException
     */
    public static void write(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        PrintWriter writer = response.getWriter();
        String jsonData = JSON.toJSONString(JSON.toJSON(ResultTool.fail(msg)));
        writer.println((jsonData));
    }


    /***
     * 返回默认错误
     * @param response
     * @throws IOException
     */
    public static void write(HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=UTF-8");

        PrintWriter writer = response.getWriter();
        String jsonData = JSON.toJSONString(ResultTool.fail());
        writer.println((jsonData));
    }
}
